//
//  XGSpeechPlugin.m
//  Runner
//
//  Created by monkey on 2019/11/4.
//  Copyright © 2019 The Chromium Authors. All rights reserved.
//

#import "XGSpeechPlugin.h"
#import "XGSpeechManager.h"

@interface XGSpeechPlugin ()

/// 语音管理对象
@property (nonatomic,strong) XGSpeechManager *speechManager;
/// flutter回调
@property (nonatomic,copy) FlutterResult result;

@end

@implementation XGSpeechPlugin

#pragma mark - FlutterPlugin

+ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar> *)registrar
{
    FlutterMethodChannel *methodChannel = [FlutterMethodChannel methodChannelWithName:@"speechPlugin" binaryMessenger:[registrar messenger]];
    [registrar addMethodCallDelegate:[[self alloc] init] channel:methodChannel];
}

- (void)handleMethodCall:(FlutterMethodCall *)call result:(FlutterResult)result
{
    if ([call.method isEqualToString:@"start"]) {
        self.result = result;
        [self.speechManager start];
    } else if ([call.method isEqualToString:@"stop"]) {
        [self.speechManager stop];
    } else if ([call.method isEqualToString:@"cancel"]) {
        [self.speechManager cancel];
    } else {
        result(FlutterMethodNotImplemented);
    }
}

#pragma mark - 懒加载

- (XGSpeechManager *)speechManager
{
    if (!_speechManager) {
        // self -> speechManager -> completion -> self 循环引用 所以用weak
        __weak typeof(self) weakSelf = self;
        _speechManager = [[XGSpeechManager alloc] initWithCompletion:^(NSString * _Nullable text, NSError * _Nullable error) {
            if (error != nil)
                weakSelf.result([FlutterError errorWithCode:@"ASR Error" message:error.localizedDescription details:nil]);
            else
                weakSelf.result(text);
            
            weakSelf.result = nil;
        }];
    }
    
    return _speechManager;
}

@end
